<template>
  <div class="task-view-container">
    <el-card shadow="never" class="header-card">
      <div class="breadcrumb">
        地铁隧道巡线车智能巡检系统 / 任务列表
      </div>
      <AppButton
          class="settings-btn"
          :icon="Setting"
          circle
          title="系统设置"
          @click="openSettingsModal"
      />
      <AppModal v-model:visible="settingsModalVisible" title="系统设置" width="600px">
        <SettingsView v-if="settingsModalVisible" @save-success="handleSettingsSaved" @cancel="handleCancel"/>
      </AppModal>
      <TaskFilter @search="handleSearch" @reset="handleReset" />
    </el-card>

    <el-card shadow="never" class="main-card">
      <div class="toolbar">
        <div class="toolbar-left">
          <AppButton type="primary" :icon="Plus" @click="handleAddNew">
            新增任务
          </AppButton>
          <AppButton type="primary" @click="goToFlawStatistics">
            缺陷统计
          </AppButton>
        </div>
      </div>

      <el-table v-loading="loading" :data="tasks" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="taskCode" label="任务编号" width="200">
          <template #default="{ row }">
            <a class="link" @click="handleViewDetail(row)">{{ row.taskCode }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="taskName" label="任务名称" show-overflow-tooltip />
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column prop="executor" label="执行人" width="120" />
        <el-table-column prop="execTime" label="执行时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.execTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="taskStatus" label="状态" width="120">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusTagType(row.taskStatus)"
              :style="row.taskStatus === TASK_STATUS.PENDING ? { color: '#c67713' } : {}"
            >
              {{ row.taskStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleStartTask(row)" v-if="row.taskStatus === TASK_STATUS.PENDING">
              启动
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)" v-if="row.taskStatus === TASK_STATUS.PENDING">
              修改
            </el-button>
            <AppButton
                type="primary"
                link
                require-confirm
                confirm-title="确定要删除这个任务吗？"
                @click="handleDelete(row)"
                v-if="row.taskStatus === TASK_STATUS.PENDING"
                custom-color="#f56565"
            >
              删除
            </AppButton>
            <el-button type="primary" link @click="handleViewDetail(row)" v-if="row.taskStatus === TASK_STATUS.COMPLETED">
              查看
            </el-button>
            <el-button type="primary" link @click="handleUpload(row)" v-if="row.taskStatus === TASK_STATUS.UPLOADING">
              上传
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-if="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          class="pagination"
          @size-change="getTasksList"
          @current-change="getTasksList"
      />
    </el-card>

    <AppModal v-model:visible="taskModalVisible" :title="modalTitle" width="800px">
      <TaskForm ref="taskFormRef" :initial-data="editableTaskData" />
      <template #footer>
        <el-button @click="taskModalVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleModalSubmit">确 定</el-button>
      </template>
    </AppModal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useTasksStore } from '@/stores/tasks';
import { storeToRefs } from 'pinia';
import { ElCard, ElTable, ElTableColumn, ElTag, ElPagination, ElButton, ElMessage } from 'element-plus';
import { Setting, Plus } from '@element-plus/icons-vue';
import { formatDateTime } from '@/utils';
import { TASK_STATUS, getStatusTagType } from '@/constants';
import TaskFilter from '@/components/task/TaskFilter.vue';
import TaskForm from '@/components/task/TaskForm.vue';
import AppModal from '@/components/common/AppModal.vue';
import AppButton from '@/components/common/AppButton.vue';
import SettingsView from "@/views/SettingsView.vue";

const router = useRouter();
const tasksStore = useTasksStore();
const { tasks, total, loading } = storeToRefs(tasksStore);
const settingsModalVisible = ref(false);

// --- State ---
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskCode: undefined,
  creator: undefined,
  executor: undefined,
  taskStatus: undefined,
});

const taskModalVisible = ref(false);
const isEditMode = ref(false);
const editableTaskData = ref(null);
const taskFormRef = ref(null); // Ref to access TaskForm component instance

// --- Computed ---
const modalTitle = computed(() => (isEditMode.value ? '修改任务' : '新增任务'));

// --- Methods ---
const getTasksList = () => {
  tasksStore.fetchTasks(queryParams);
};

const handleSearch = (filters) => {
  queryParams.pageNum = 1;
  Object.assign(queryParams, filters);
  getTasksList();
};

const openSettingsModal = () => {
  settingsModalVisible.value = true;
};

const handleSettingsSaved = () => {
  settingsModalVisible.value = false;
  ElMessage.info('配置已更新');
};

const handleCancel = () => {
  settingsModalVisible.value = false;
};

const handleReset = () => {
  queryParams.pageNum = 1;
  queryParams.taskCode = undefined;
  queryParams.creator = undefined;
  queryParams.executor = undefined;
  queryParams.taskStatus = undefined;
  getTasksList();
};

const goToSettings = () => {
  router.push('/settings');
};

const goToFlawStatistics = () => {
  router.push('/statistics');
};

const handleAddNew = () => {
  isEditMode.value = false;
  editableTaskData.value = null; // Pass null for new task
  taskModalVisible.value = true;
};

const handleEdit = (row) => {
  isEditMode.value = true;
  editableTaskData.value = { ...row }; // Pass a copy for editing
  taskModalVisible.value = true;
};

const handleDelete = async (row) => {
  await tasksStore.deleteTask(row.id);
  // The store action will refresh the list
};

const handleViewDetail = (row) => {
  router.push(`/tasks/detail/${row.id}`);
};

const handleStartTask = async (row) => {
  console.log("handle start")
  let success = await tasksStore.startNewTask(row.id);
  console.log("start end")
  if(success) {
    router.push(`/tasks/execute/${row.id}`);
  }
}

const handleUpload = async (row) => {
  console.log("row",row.id)
  let {code} = await tasksStore.uploadCurrTask(row.id)
  console.log("code",code)
  if(code === 200 || code === "200"){
    ElMessage.success("任务上传成功")
    getTasksList()
  }
}

const handleModalSubmit = async () => {
  const form = taskFormRef.value?.formRef;
  if (!form) return;

  await form.validate(async (valid) => {
    if (valid) {
      const formData = taskFormRef.value.formModel;
      let success = false;
      if (isEditMode.value) {
        success = await tasksStore.updateTaskData(formData);
      } else {
        success = await tasksStore.createTask(formData);
      }

      if (success) {
        taskModalVisible.value = false;
      }
    }
  });
};

// --- Lifecycle ---
onMounted(() => {
  getTasksList();
});
</script>

<style lang="scss" scoped>
@use '../assets/scss/variables' as *;

.task-view-container {
  padding: $page-padding;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: $page-padding;
}

.header-card {
  position: relative;
  flex-shrink: 0; // Prevent header from shrinking
}

.main-card {
  flex: 1; // Allow main card to grow and fill space
  display: flex;
  flex-direction: column;
  overflow: hidden; // Prevent content from overflowing the card

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.breadcrumb {
  margin-bottom: 20px;
  color: $text-color-regular;
  font-size: $font-size-base;
}

.settings-btn {
  position: absolute;
  top: 15px;
  right: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .toolbar-left,
  .toolbar-right {
    display: flex;
    gap: 10px;
  }
}

.link {
  color: $primary-color;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
  flex-shrink: 0; // Prevent pagination from shrinking
}
</style>